//
//  DetailExeViewController.m
//  CloudMD
//
//  Created by apple on 16/2/18.
//  Copyright (c) 2016年 HuaZhengInfo. All rights reserved.
//

#import "DetailExeViewController.h"
#import "FinishTableViewCell.h"
#import "ScanTableViewCell.h"
#import "InforTableViewCell.h"
#import "GDScanViewController.h"
#import "GYLAddImage.h"
#import "BeforeInfoTableViewCell.h"
#import "ExecuteOrderViewController.h"

@interface DetailExeViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIAlertViewDelegate>{

    UITableView * _tableView;
    NSMutableArray * _dataArray;
    NSString * _state; //  状态
    NSMutableArray * _beforeImageArray; // 处理前图片数组
    NSMutableArray * _lateImageArray;   // 处理后图片数组
    NSString * _beforeID; // 处理前图片ID
    NSString * _lateID;  // 处理前图片ID
    
}

@end

@implementation DetailExeViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单执行";
    
    // 导航栏左按钮
    UIButton * leftButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, 10, 15) backImage:@"left_arrow" title:nil titleLableColcor:nil titleLabelFont:nil];
    [leftButton addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    // 初始化
    _dataArray = [NSMutableArray array];
    _beforeImageArray = [NSMutableArray array];
    _lateImageArray = [NSMutableArray array];
    
//    _GUID = [[NSString alloc] init];
//    _ID = [[NSString alloc] init];
    _beforeID = [[NSString alloc] init];
    _lateID = [[NSString alloc] init];
    _state = @"SUCCESS";
    [self buildUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_tableView reloadData];
}



#pragma mark --- 请求订单执行数据
- (void)requestData{

    NSArray * keyArray = @[@"GUID",@"USER_ID",@"USER_CODE",@"TYPE",@"REMARK",@"ATTACHMENT"];
    NSUserDefaults * textFaults = [NSUserDefaults standardUserDefaults];
    NSString * remark = [textFaults objectForKey:@"TEXT"];
//    NSLog(@"%@",remark);
    NSArray * valueArray = @[_GUID,USER_ID,USER_CODE,@"",remark,@""];
    
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,MyOrderDo_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * datadict in array) {
            
            _state = [datadict objectForKey:@"STATUS"];
        }
        if ([_state isEqualToString:@"SUCCESS"]) {
            
            [MBProgressHUD HUDShowMessage:@"提交成功" addedToView:self.navigationController.view];
            
            [_tableView reloadData];
            //图片上传
            [self upLoadImage];
            [self.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"OrderExecuteRefreshNotification" object:nil];
        }else{
            
            [MBProgressHUD HUDShowMessage:@"提交失败" addedToView:self.navigationController.view];
        }
    } withTag:101];
    
}

#pragma mark -- 上传图片

- (void)upLoadImage{
    
    NSArray * keyArray = @[@"ID",@"MODULE",@"ATTACHMENT"];
    
    if (_beforeImageArray.count > 0) {
        
        for (NSData * imageData in _beforeImageArray) {
            
            NSString * imageStr = [imageData base64Encoding];
            NSArray * valueArray = @[_ID,@"beforeOrderExec",imageStr];
            NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,UploadAttachment_URL];
            
            HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
            [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
                NSMutableArray * array = [http.returnArray mutableCopy];
//                for (NSDictionary * dataDict in array) {
//                    _beforeID = [dataDict objectForKey:@"ID"];
//                    
//                }
            } withTag:101];
            
        }

    }
    
    if (_lateImageArray.count > 0) {
        
        for (NSData * imageData in _lateImageArray) {
            
            NSString * imageStr = [imageData base64Encoding];
            NSArray * valueArray = @[_ID,@"afterOrderExec",imageStr];
            NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,UploadAttachment_URL];
            HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
            [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
                NSMutableArray * array = [http.returnArray mutableCopy];
//                for (NSDictionary * dataDict in array) {
//                    _lateID = [dataDict objectForKey:@"ID"];
//                }
            } withTag:101];
            
         }
    }
    
}

#pragma mark -- 创建UI
- (void)buildUI{

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H - 64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = RGBA(235, 235, 235, 1.0);
    //隐藏分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCR_W,SCR_H / 6)];
    footView.backgroundColor = RGBA(235, 235, 235, 1.0);
    
    UIButton * finshBtn = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, SCR_W/2, 40) backImage:@"3在线下单" title:@"提交完成" titleLableColcor:[UIColor whiteColor] titleLabelFont:[UIFont systemFontOfSize:18]];
    finshBtn.center = footView.center;
    [finshBtn addTarget:self action:@selector(clickFinsh) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:finshBtn];
    

    _tableView.tableFooterView = footView;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString * ID = @"GD";
    if (indexPath.section == 0) {
        FinishTableViewCell * cell0 = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell0 == nil) {
            cell0 = [[FinishTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        NSString * text = cell0.textView.text;
        NSUserDefaults * textFaults = [NSUserDefaults standardUserDefaults];
        [textFaults setObject:text forKey:@"TEXT"];
        cell0.backgroundColor = RGBA(235, 235, 235, 1.0);
        cell0.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell0;
        
    }
//    if (indexPath.section == 1) {
//        ScanTableViewCell * cell1 = [tableView dequeueReusableCellWithIdentifier:ID];
//        if (cell1 == nil) {
//            cell1 = [[ScanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        }
//        cell1.backgroundColor = RGBA(235, 235, 235, 1.0);
//        return cell1;
//        
//    }
    if (indexPath.section == 1)
    {
    
        BeforeInfoTableViewCell * cell2 = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell2 == nil) {
            cell2 = [[BeforeInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }

        // 获取图片数组
//        NSUserDefaults * imageFaults = [NSUserDefaults standardUserDefaults];
//        NSMutableArray * imageArray = cell2.addImageView.imageDataArr;
//        [imageFaults setObject:imageArray forKey:@"BEFORE"];
        
        _beforeImageArray = cell2.addImageView.imageDataArr;
        cell2.backgroundColor = RGBA(235, 235, 235, 1.0);
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof(self) weakSelf = self;
        cell2.addImageView.block = ^(UIViewController *pickerVC){
            [weakSelf presentViewController:pickerVC animated:YES completion:nil];
        };
        return cell2;
    }
    else {
        
        InforTableViewCell * cell3 = [tableView dequeueReusableCellWithIdentifier:ID];
    
        if (cell3 == nil) {
            cell3 = [[InforTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        // 获取图片数组
        _lateImageArray = cell3.addImageView.imageDataArr;
        cell3.backgroundColor = RGBA(235, 235, 235, 1.0);
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof(self) weakSelf = self;
        cell3.addImageView.block = ^(UIViewController *pickerVC){
            [weakSelf presentViewController:pickerVC animated:YES completion:nil];
        };
        return cell3;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView * headerView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, SCR_W, 30) backColor:[UIColor clearColor]];
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, tableView.frame.size.width - 20, 30)];
    headerLabel.textAlignment = NSTextAlignmentLeft;
    headerLabel.textColor = RED;
    headerLabel.font = [UIFont systemFontOfSize:16];
//    headerLabel.backgroundColor = [UIColor redColor];
    if (section == 0) {
        headerLabel.text = @"完成情况:";
    }
//    if (section == 1) {
//        headerLabel.text = @"二维码扫描定位";
//    }
    if (section == 1) {
        headerLabel.text = @"处理前资料:";
    }
    if (section == 2) {
        headerLabel.text = @"处理后资料:";
    }
    [headerView addSubview:headerLabel];
    return headerView;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return @"lala";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        return SCR_H/6;

    } else{
    
        return SCR_H/5;
    }
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    FinishTableViewCell * cell = [[FinishTableViewCell alloc] init];
    [cell.textView resignFirstResponder];
}


#pragma mark -- 提交完成
- (void)clickFinsh{
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    FinishTableViewCell *cell = (FinishTableViewCell *)[_tableView cellForRowAtIndexPath:index];
    if ([cell.textView.text isEqualToString:@""]) {
        [MBProgressHUD HUDShowMessage:@"请输入完成情况" addedToView:self.view];
        return;
    }
    if (_beforeImageArray.count == 0) {
        [MBProgressHUD HUDShowMessage:@"请添加处理前资料" addedToView:self.view];
        return;
    }
    if (_lateImageArray.count == 0) {
        [MBProgressHUD HUDShowMessage:@"请添加处理后资料" addedToView:self.view];
        return;
    }
    
    [self alertError:@"确认提交？"];
    
    
}

#pragma mark - 弹框提示
- (void)alertError:(NSString *)error{
    // 1.弹框
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:error delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        
        [self requestData];
    }
}

#pragma clickLeft
- (void)clickLeft{

    [self.navigationController popViewControllerAnimated:YES];
}

@end
